package com.xuetang9.fujian.socketdemo.tcpdemo.onetomore;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author: fujian
 * @description:
 * @date: 2021/5/10 9:18
 * @version: V1.0
 * @package: com.xuetang9.fujian.socketdemo.tcpdemo.onetomore
 **/
public class SocketHandler implements Runnable{
    private static int counter = 1;
    private Socket socket;          // 客户端连接对象
    private ObjectInputStream inStream;
    private ObjectOutputStream outStream;
    private String clientName;
    public SocketHandler(Socket socket) {
        this.socket = socket;
        this.clientName = "客户端" + counter++;
        try {
            outStream = new ObjectOutputStream(socket.getOutputStream());
            inStream = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        Object data = null;
        while (true) {
            try {
                if ((data = inStream.readObject()) != null){
                    System.out.println("接收到来自<" + clientName + ">的消息" + data);
                }
                if (!CommandStore.ReplyMap.containsKey(data)){
                    outStream.writeObject("小爱还很年轻，要学的东西还很多，不明白你的意思");
                }else {
                    outStream.writeObject(CommandStore.ReplyMap.get(data));
                }
                outStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

    }
}
